<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="query">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="add">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" border="" stripe="">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="inputchange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div class="actions">
              <i class="el-icon-edit" @click="xiugai(row.id)"></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
              <i class="el-icon-s-tools" @click="fenpei(row)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pagesize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addclose"
    >
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="ruleFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input> </el-form-item
        ><el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input> </el-form-item
        ><el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="xiugaidialogVisible"
      width="50%"
      @close="xiugaiclose"
    >
      <el-form
        :model="xiugaiForm"
        :rules="xiugairules"
        ref="xiugaiFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="xiugaiForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="xiugaiForm.email"></el-input> </el-form-item
        ><el-form-item label="手机号" prop="mobile">
          <el-input v-model="xiugaiForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="xiugaidialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="xiugaiqueren">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配" :visible.sync="fenpeidialogVisible" width="50%">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectfenpei" placeholder="请选择">
            <el-option
              v-for="item in fenpeilist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer" @close="fpchongzhi">
        <el-button @click="fenpeidialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="fenpeiqueren()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getlist1 } from "../../api/user";
import { getstustas } from "../../api/user";
import {
  getadd,
  getxiugai,
  getxiugaidiyi,
  getshanchu,
  getfenpei,
  getfenpeiid,
} from "../../api/user";
export default {
  name: "UserIndex",
  data() {
    return {
      query: "",
      pagenum: 1,
      pagesize: 2,
      userlist: [],
      total: 0,
      xiugaidialogVisible: false,
      dialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      xiugaiForm: {
        username: "",
        email: "",
        mobile: "",
      },
      addrules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
            // validator: checkEmail,
            pattern:
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
          },
          // { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            // validator: checkMobile,
          },
          // { validator: checkMobile, trigger: "blur" },
        ],
      },
      xiugairules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
            // validator: checkEmail,
            pattern:
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
          },
          // { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            // validator: checkMobile,
          },
          // { validator: checkMobile, trigger: "blur" },
        ],
      },
      //分配
      fenpeidialogVisible: false,
      userInfo: {},
      fenpeilist: [],
      selectfenpei: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      const res = await getlist1({
        pagenum: this.pagenum,
        pagesize: this.pagesize,
        query: this.query,
      });
      // console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
      // console.log(res.data.users);
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.getList();
    },
    async inputchange(e) {
      const id = e.id;
      const sta = e.mg_state;
      const res1 = await getstustas(id, sta);
      if (res1.meta.status !== 200) {
        e.mg_state = !e.mg_state;
        return this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
    },
    add() {
      this.dialogVisible = true;
    },
    addclose() {
      this.$refs.ruleFormRef.resetFields();
    },
    async addUser() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        const res2 = await getadd(this.addForm);
        // console.log(valid);
        if (valid) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.getList();
          // console.log(res2);
        }
        if (res2.meta.status !== 201) {
          this.$message.error("添加失败");
        }
      });
    },
    async xiugai(id) {
      this.xiugaidialogVisible = true;
      const xiu = await getxiugai(id);
      // console.log(xiu);
      this.xiugaiForm = xiu.data;
      // console.log(this.xiugaiForm);
    },
    xiugaiclose() {
      this.$refs.xiugaiFormRef.resetFields();
    },
    xiugaiqueren() {
      this.$refs.xiugaiFormRef.validate(async (valid) => {
        // console.log(valid);
        const rea = await getxiugaidiyi(this.xiugaiForm);
        // console.log(rea);
        if (valid) {
          this.$message.success("修改成功");
          this.xiugaidialogVisible = false;
          this.getList();
        }
        if (rea.meta.status !== 200) {
          this.$message.error("修改失败");
        }
      });
    },
    async del(id) {
      const quxiao = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      if (quxiao !== "confirm") {
        return this.$message.info("取消删除");
      }
      // console.log(quxiao);
      const ii = await getshanchu(id);
      console.log(ii);
      this.$message.success("删除成功");
      this.getList();
    },
    async fenpei(userInfo) {
      this.fenpeidialogVisible = true;
      const fenpei = await getfenpei();
      console.log(fenpei);
      this.fenpeilist = fenpei.data;
      this.userInfo = userInfo;
      console.log(userInfo);
    },
    async fenpeiqueren() {
      // console.log(this.userInfo.id);
      const id = await getfenpeiid(this.userInfo.id, {
        rid: this.selectfenpei,
      });
      console.log(id);
      if (id.meta.status !== 200) {
        return this.$message.error("更新失败");
      }
      this.$message.success("更新成功");
      this.fenpeidialogVisible = false;
      this.getList();
    },
    fpchongzhi() {
      this.userInfo = {};
      this.selectfenpei = [];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-table {
  margin-top: 15px;
}
.actions {
  font-size: 18px;
  display: flex;
  justify-content: space-around;
  color: #666;
  > i:hover {
    color: rgba(114, 124, 245, 1);
    cursor: pointer;
  }
}
</style>
